const urlencode = require('urlencode');
const axios = require('axios')
const { CODE_ERROR, CODE_SUCCESS, PRIVATE_KEY, JWT_EXPIRED } = require('./constant');
const { Token, AppId, AppSecret, Url } = require('../config/index');



//用户信息失效，重新获取code
function redirectGetCode(req, res) {
    const redirct_url = `${Url}/api/getCode`;
    const temp_url = urlencode(redirct_url);
    res.redirect(301, `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${AppId}&redirect_uri=${temp_url}&response_type=code&scope=snsapi_base&state=TaskReceipts#wechat_redirect`);
}



//通过code换取用户信息和access_token
async function getWxUserOpenId(current_code) {
    /**
     *https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
     */
    try {
        const result = await axios({
            method: 'get',
            url: 'https://api.weixin.qq.com/sns/oauth2/access_token',
            params: {
                appid: AppId,
                secret: AppSecret,
                code: current_code,
                grant_type: 'authorization_code',
            }
        })
        return result;
    } catch (error) {
        return '请求出错' + error;
    }
}


module.exports = {
    redirectGetCode,
    getWxUserOpenId
}